#include "tcpserver.h"
#include "ui_tcpserver.h"
#include<QtSql>
#include <QHostInfo>
tcpserver::tcpserver(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tcpserver)
{
    ui->setupUi(this);
    this->setWindowTitle(" My QQChart Server");
    //创建数据库
    const char* myQQDBFilePath = "D:/code/c++/database_work/build-QQServer-Desktop_Qt_5_15_2_MinGW_64_bit-Debug/MyQQChart.db";


    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//返回一条新建立的数据库连接
    db.setDatabaseName(myQQDBFilePath);//设置数据库的文件名
    bool bRet = db.open();//打开连接
    if (!bRet){
             printf("QtSql driver <QSQLITE> cannot open %s\n", myQQDBFilePath);
             return ;
     }
     QSqlQuery query;//可以用SQL语言直接驱动这个数据库
     QFile file(myQQDBFilePath);
     //创建初始表
     if(file.size()==0)
     {
         //创建user表
         const char* CreateUserInfoTable = "create table user(u_id int primary key,u_name varchar(20) not null, u_password varchar(20) not null,u_sex int check (u_sex in (0, 1)),u_signature varchar(20),"
                 "u_userstateid int,foreign key(u_userstateid) references userstate(us_id));" ;
         if(!query.exec(CreateUserInfoTable)){//执行SQL语句
             printf(query.lastError().text().toStdString().c_str());
             return ;
         };
        //创建user state表
          const char* CreateUserstateTable = "create table userstate(us_id int primary key,us_name varchar(10));";
         if(!query.exec(CreateUserstateTable)){//执行SQL语句
             printf(query.lastError().text().toStdString().c_str());
             return ;
         };
         //对userstatetable 进行数据填充
        query.prepare("insert into userstate(us_id,us_name) values(:us_id,:us_name)");
        query.bindValue(":us_id",0);
        query.bindValue(":us_name","离线");
        if(!query.exec()){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        query.prepare("insert into userstate(us_id,us_name) values(:us_id,:us_name)");
        query.bindValue(":us_id",1);
        query.bindValue(":us_name","在线");
        if(!query.exec()){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建 friend表
        const char* CreateFriendTable = "create table friend(f_friendid int ,f_userid int ,f_name varchar(20),f_friendtypeid int,f_friendgroupsid int, "
                                        "primary key(f_friendid,f_userid),foreign key(f_friendtypeid)references friendtype(ft_id),"
                                        "foreign key(f_friendgroupsid) references friendgroups(fg_id),"
                                        "foreign key(f_friendid) references user(u_id),"
                                        "foreign key(f_userid) references user(u_id));";
        if(!query.exec(CreateFriendTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建friendtype表格
        const char* CreateFriendTypeTable = "create table friendtype(ft_id int primary key,ft_name varchar(10));";
        if(!query.exec(CreateFriendTypeTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //为friendtype表格添加内容
        query.prepare("insert into friendtype(ft_id,ft_name) values(:ft_id,:ft_name)");
        query.bindValue(":ft_id",0);
        query.bindValue(":ft_name","普通好友");
        if(!query.exec()){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        query.prepare("insert into friendtype(ft_id,ft_name) values(:ft_id,:ft_name)");
        query.bindValue(":ft_id",1);
        query.bindValue(":ft_name","特别关注");
        if(!query.exec()){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建friendgroups表
        const char* CreateFriendgroupsTable = "create table friendgroups(fg_id int primary key,fg_name varchar(10),fg_userid int,"
                                              "foreign key(fg_userid) references user(u_id));";//好友组的创建还是一个大问题
        if(!query.exec(CreateFriendgroupsTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建messages表
        const char* CreatemessagesTable = "create table messages(m_postmessage text,m_time datetime,m_fromuserid int,m_touserid int,"
                                          "foreign key(m_fromuserid) references user(u_id),"
                                          "foreign key(m_touserid) references user(u_id),"
                                          "primary key(m_time,m_fromuserid,m_touserid));";
        if(!query.exec(CreatemessagesTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建user_group表
        const char* Createuser_groupTable = "create table user_group(ug_id int primary key,ug_name varchar(30),ug_adminid int,ug_createtime datetime,"
                                          "foreign key(ug_adminid) references user(u_id));";
        if(!query.exec(Createuser_groupTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建user_grouptouser表
        const char* Createuser_grouptouserTable = "create table user_grouptouser(ug_userid int,ug_groupid int,ug_groupnick varchar(20),"
                                          "foreign key(ug_userid) references user(u_id),"
                                                  "foreign key(ug_groupid) references user_group(ug_id),"
                                                  "primary key(ug_userid,ug_groupid));";
        if(!query.exec(Createuser_grouptouserTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
        //创建user_groupmsgcontent表
        const char* Createuser_groupmsgcontentTable = "create table user_groupmsgcontent(gm_content text,gm_groupid int,gm_fromid int,gm_fromusername varchar(10),gm_createtime datetime,"
                                          "foreign key(gm_fromid) references user(u_id),"
                                          "foreign key(gm_groupid) references user_group(ug_id),"
                                          "primary key(gm_createtime,gm_fromid,gm_groupid));";
        if(!query.exec(Createuser_groupmsgcontentTable)){//执行SQL语句
            printf(query.lastError().text().toStdString().c_str());
            return ;
        };
     }
     //启动服务器

     server = new Server;//服务器处理程序
     QString LocalIP=getLocalIP();
//监听本机所有网口的8888号端口
     if(server->listen(QHostAddress::Any,8888))
     {
         ui->textEdit->append("QQChart服务器正在运行！");
     }
}

tcpserver::~tcpserver()
{
    delete ui;
}

QString tcpserver::getLocalIP()
{
    QString hostName=QHostInfo::localHostName();
    QHostInfo hostInfo=QHostInfo::fromName(hostName);
    QString localIP="";
    QList<QHostAddress> addList=hostInfo.addresses();
    if(!addList.isEmpty())
    {
        for(int i=0;i<addList.count();i++)
        {
            QHostAddress aHost=addList.at(i);
            if(QAbstractSocket::IPv4Protocol==aHost.protocol())
            {
                localIP=aHost.toString();
                break;
            }
        }
    }
    return localIP;
}
